package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.FreemarkerService;
import com.heima.common.redis.CacheService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author 陈辉
 * @data 2023 11:22
 */
@Service
@Transactional
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    @Autowired
    private ApArticleMapper apArticleMapper;
    @Autowired
    private ApArticleContentMapper apArticleContentMapper;
    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;
    @Autowired
    private FreemarkerService freemarkerService;
    @Autowired
    private CacheService cacheService;

    /**
     * 加载首页              type  1
     *
     * @param homeDto
     * @return 加载更新       type  2
     * @return 加载更多       type  1
     */
    @Override
    public ResponseResult load(ArticleHomeDto homeDto, int type) {
        //1. 参数校验
        if (homeDto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2. 数据处理
        if (homeDto.getMaxBehotTime() == null) {
            homeDto.setMaxBehotTime(new Date(0L));
        }
        if (homeDto.getMinBehotTime() == null) {
            homeDto.setMinBehotTime(new Date());
        }
        if (homeDto.getSize() == null || homeDto.getSize() <= 0) {
            homeDto.setSize(10);
        } else {
            homeDto.setSize(Math.min(homeDto.getSize(), 50));   //防止分页条数过大，限制每页最大50条
        }

        //3. 调用mapper层处理数据
        List<ApArticle> list = apArticleMapper.loadArticleList(homeDto, type);

        //4. 返回结果
        return ResponseResult.okResult(list);
    }

    /**
     * 首页加载热点文章
     *
     * @param homeDto
     * @param loadtypeLoadMore
     * @return
     */
    @Override
    public ResponseResult loadHotArticle(ArticleHomeDto homeDto, Short loadtypeLoadMore) {

        //从redis中加载热点文章数据
        String hotArticleJSON = cacheService.get("hot_article_" + homeDto.getTag());
        if (StringUtils.isNotBlank(hotArticleJSON)){
            List list = JSON.parseObject(hotArticleJSON, List.class);
            return ResponseResult.okResult(list);
        }else{
            //缓存没有就还走原本的查数据库的逻辑
            return load(homeDto,loadtypeLoadMore);
        }
    }

    /**
     * 同步自媒体文章到app端
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveArticle(ArticleDto dto) {

        String articleId = String.valueOf(dto.getId());

        //1. 判断dto有没有id： 有，修改; 没有，新增
        if (dto.getId() != null) {
            //修改
            //修改文章基本信息： ap_article
            ApArticle apArticle = new ApArticle();
            BeanUtils.copyProperties(dto, apArticle);
            updateById(apArticle);

            //修改文章内容： ap_article_content
            ApArticleContent apArticleContent = apArticleContentMapper
                    .selectOne(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, dto.getId()));

            apArticleContent.setContent(dto.getContent());
            apArticleContentMapper.updateById(apArticleContent);
        } else {
            //新增
            //新增文章基本信息: ap_article
            ApArticle apArticle = new ApArticle();
            BeanUtils.copyProperties(dto, apArticle);
            save(apArticle);

            //新增文章配置: ap_article_config
            ApArticleConfig apArticleConfig = new ApArticleConfig(apArticle.getId());
            apArticleConfigMapper.insert(apArticleConfig);

            //新增文章内容: ap_article_content
            ApArticleContent content = new ApArticleContent();
            content.setArticleId(apArticle.getId());
            content.setContent(dto.getContent());
            apArticleContentMapper.insert(content);

            articleId = String.valueOf(apArticle.getId());
        }

        //3. 生成文章的详情页
        //方法同步调用：阻塞式
        //方法异步调用：非阻塞式
        freemarkerService.buildDetailsPage(dto.getContent(), Long.valueOf(articleId));

        return ResponseResult.okResult(articleId);
    }
}
